import {
    getProject
} from '../../../api/app.js'
import {
    getFlowUUID,
    createPayFlow,
    getLongProjectDate,
    getLongProjectWorker,
    setProjectWorkerTop,
    getPayWorkerList,
    getCompanySingleQuota
} from '../../api/pay'
import {
    inputchange,
    dateFormat,
    anit,
    shake
} from '../../../utils/util'
import {
    queryFontLetter
} from '../../../utils/pinyin'
import user from '../../../utils/user'

const app = getApp()
Page({
    data: {
        uuid: 0,
        date: '',
        companyName: '',
        projectNum: '',
        workers: [],
        showWorkers: [],
        women: '',
        men: '',
        workerCount: '',
        remarks: '',
        countPayPrice: 0,
        countPayPeople: 0,
        selectAllStatus: false,
        payStatus: false,
        setPriceStatus: false,
        setRemarkStatus: false,
        workerPrice: null,
        selectIds: {},
        priceData: {},
        type: 0,
        longDate: 0,
        todoList: [],
        longSelectDate: '',
        isRepeatTip: false,
        // 选择条件
        showSelectTypeStatus: false,
        selectTypeList: [{
            text: '全选',
            callback: 'selectAll'
        },
        {
            text: '达成条件',
            callback: 'selectLongDayReachAll'
        },
        {
            text: '已调薪',
            callback: 'selectSetAll'
        },
        {
            text: '性别男',
            callback: 'selectMale'
        },
        {
            text: '性别女',
            callback: 'selectFemale'
        },
        ],
        letter: ['#', 'A', 'B', 'C', 'D', 'E', 'F', 'E', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],
        dragX: 1000,
        isAdmonish: false,
        amountLimit: '20000'
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            projectId: options.id,
            type: Number(options.type),
            selectIds: new Map(),
            priceData: new Map(),
            longDate: options.longDate || 0,
            processId: options.processId || ''
        })
        // 获取发薪金额限制接口 先不上
        this.onGetCompanySingleQuota()
        console.log('type', options.type)
        // 短期工初始化
        if (Number(options.type) === 0) {
            this.dayInit()
        }
        // 长期工初始化
        else {
            const date = dateFormat('YYYY-mm-dd', new Date())
            if (options.longDate) {
                this.getFlowUUID()
                this.getLongProjectWorker(options.longDate)
                this.setData({
                    date: options.longDate
                })
            } else {
                this.getLongProjectDate(date)
            }
        }
    },
    // 更新todo
    getLongProjectDate(date) {
        getLongProjectDate({
            date,
            projectId: this.data.projectId || ''
        }).then(res => {
            const todo = {}
            for (const i in res) {
                todo[res[i]] = true
            }
            this.setData({
                todoList: todo
            })
            console.log(this.data.todoList, 'todoList')
        })
    },
    // 获取发薪金额限制
    async onGetCompanySingleQuota () {
        const result = await getCompanySingleQuota()
        console.log(result, 'resultresultresultresult')
        this.setData({
            amountLimit: result
        })
    },
    // 获取发薪流程单号
    getFlowUUID() {
        getFlowUUID().then(res => {
            console.log(res)
            this.setData({
                uuid: res
            })
        })
    },
    // 短期工初始化
    dayInit() {
        this.getFlowUUID()
        // 获取项目信息
        getProject({
            id: this.data.projectId
        }).then((res) => {
            // 判断是否为当天之前的项目
            const isOld = new Date(res.createTime).getTime() < new Date(new Date().toLocaleDateString()).getTime()
            this.setData({
                date: res.date,
                companyName: res.serveCompanyName,
                projectNum: res.projectNum,
                leader: res.params.lead,
                billingPolicy: res.billingPolicy,
                recipient: res.recipient,
                type: ((res.type === 0|| res.type === 2) ? 0 : 1),
                isOld,
                isRepeatTip: res.isOpenPayRepeatReminder
            })
        })
        // 获取显示员工信息
        this.getProjectWorker()
    },
    // 获取员工列表，用于显示和搜索
    getProjectWorker(value = undefined) {
        getPayWorkerList({
            projectId: this.data.projectId || '',
            searchText: value || '',
            processId: this.data.processId
        }).then(res => {
            console.log(res)
            for (const i in res.list) {
                res.list[i].userId = res.list[i].userId + ''
                // 时间格式化
                if (res.list[i].signTimeIn) {
                    res.list[i].signTimeIn = res.list[i].signTimeIn.split(' ')[1]
                }
                if (res.list[i].signTimeOut) {
                    res.list[i].signTimeOut = res.list[i].signTimeOut.split(' ')[1]
                }

                // 数据还原
                if (this.data.priceData.has(res.list[i].userId)) {
                    res.list[i].price = this.data.priceData.get(res.list[i].userId)
                } else {
                    res.list[i].price = null
                }
                if (this.data.selectIds.has(res.list[i].userId)) {
                    res.list[i].selected = this.data.selectIds.has(res.list[i].userId)
                } else {
                    res.list[i].selected = false
                }
            }
            this.setData({
                showWorkers: this.initShowWorkers(res.list),
                women: res.women,
                men: res.men,
                workerCount: res.count
            })
            if (value === undefined) {
                this.setData({
                    workers: this.initWorkers(res.list),
                    companyName: res.projectName
                })
            }
            if(this.data.processId)
                this.useLastRule('force')
        })
    },
    // 长期工日期切换
    onLongDateChange(event) {
        console.log(event, 'event长期工日期切换')
        this.setData({
            longSelectDate: event.detail
        })
        this.getLongProjectWorker(event.detail)

    },
    // 获取长期工人员列表
    getLongProjectWorker(date, search = undefined) {
        console.log(this.data.projectId, 'this.data.projectId')
        const data = {
            projectId: this.data.projectId,
            nowDate: date,
            searchText: search || '',
            processId: this.data.processId
        }
        getLongProjectWorker(data).then(res => {
            if(!res.list) {
                return
            }
            for (const i in res.list) {
                // 将USERID格式化为字符串
                res.list[i].userId = res.list[i].userId + ''
                // 时间格式化
                if (res.list[i].signTimeIn) {
                    res.list[i].signTimeIn = res.list[i].signTimeIn.split(' ')[1]
                }
                if (res.list[i].signTimeOut) {
                    res.list[i].signTimeOut = res.list[i].signTimeOut.split(' ')[1]
                }
                // 搜索还原之前的数据
                if (this.data.priceData.has(res.list[i].userId)) {
                    res.list[i].price = this.data.priceData.get(res.list[i].userId)
                } else {
                    res.list[i].price = null
                }
                if (this.data.selectIds.has(res.list[i].userId)) {
                    res.list[i].selected = this.data.selectIds.has(res.list[i].userId)
                } else {
                    res.list[i].selected = false
                }
            }
            this.setData({
                showWorkers: this.initShowWorkers(res.list),
                women: res.women,
                men: res.men,
                workerCount: res.count,
            })
            if (search === undefined) {
                this.setData({
                    workers: this.initWorkers(res.list),
                    companyName: res.projectName
                })
            }
            if(this.data.processId)
                this.useLastRule('force')
        })
    },
    hideRemarkPopup() {
        this.setData({
            setRemarkStatus: false,
            remarks: ''
        })
    },
    // 清洗备份数据
    initWorkers(list) {
        const data = {}
        for (const item of list) {
            item.userName = item.workerName
            item.dragX = 1000
            // item.workerName = item.workerName + '（' + item.idCardNo.slice(-4) + '）'
            data[item.userId] = item
        }
        return data
    },
    initShowWorkers(list) {
        // 清洗到字母表中
        const data = {
            length: 0
        }
        for (let letter of this.data.letter) {
            // 增加对象长度字段判断wxml显示
            if (letter === '#') {
                letter = '置顶'
            }
            data[letter] = {
                length: 0
            }
        }
        for (const i in list) {
            // 增加对象长度字段判断wxml显示
            data.length += 1
            // 查询首字母
            const letter = queryFontLetter(list[i].workerName)[0][0]
            data[letter][list[i].userId] = list[i]
            data[letter].length += 1
            if (list[i].isOnTheTop) {
                data['置顶'].length += 1
                data['置顶'][list[i].userId] = list[i]
            }
        }
        return data
    },

    // 使用上次规则
    // 循环workers数组中的所有数据，将priceData中的
    onUseLastRule() {
        app.confirm('是否确认使用上次发薪规则，这将会使您失去当前调薪记录').then(() => {
            for (const i in this.data.workers) {
                if (this.data.workers[i].paymentAmount && this.data.workers[i].paymentAmount >  this.data.amountLimit) {
                    app.alert('上次发薪规则金额，超出当前设置金额上限')
                    return
                }
            }
            this.useLastRule()
        })
    },
    useLastRule(force = false) {
        // 使用上次发薪规则清空所有现有数据
        const selectIds = new Map()
        const priceData = new Map()
        // 标志位，用于标识上次是否有记录
        let status = false
        for (const i in this.data.workers) {
            if (this.data.workers[i].paymentAmount ) {
                status = true
                this.data.workers[i].price = this.data.workers[i].paymentAmount
                priceData.set(this.data.workers[i].userId, this.data.workers[i].paymentAmount)
                // 注销用户恢复金额但不勾选
                if(!this.data.workers[i].isLogout) {
                    this.data.workers[i].selected = true
                    selectIds.set(this.data.workers[i].userId, true)
                }
            } else {
                this.data.workers[i].selected = false
                selectIds.delete(this.data.workers[i].userId)
                priceData.delete(this.data.workers[i].userId)
            }
        }
        if (!status) {
            app.toast('暂无上次发薪记录')
        } else {
            this.setData({
                selectIds,
                priceData,
                workers: this.data.workers,
                selectAllStatus: true
            })
            this.upPayStatus()
            // 自动强制更新不做提示
            if(!force)
                app.toast('规则更新成功', 'success')
        }
    },
    // 切换人员选择
    checkSelected(event) {
        const userId = event.currentTarget.dataset.index
        const worker = this.data.workers[userId]
        if (this.data.selectIds.has(userId)) {
            this.data.selectIds.delete(userId)
        } else {
            if(this.data.isRepeatTip && worker.isPaySent) {
                wx.showModal({
                    title: '确定重复发薪？',
                    content: '已发过，确定重复发薪？',
                    confirmText: '继续发薪',
                    success: (res) => {
                        if (res.confirm) {
                            this.setData({
                                ['workers.' + userId + '.selected']: !worker.selected
                            })
                            this.data.selectIds.set(userId, true)
                            this.selectUpdate()
                        }
                    }
                })
                return
            }
            else{
                this.data.selectIds.set(userId, true)
            }
        }
        this.setData({
            ['workers.' + userId + '.selected']: !worker.selected
        })
        this.selectUpdate()
    },
    selectUpdate() {
        this.setData({
            selectIds: this.data.selectIds
        })

        // 更新总人数和总价格
        this.upPayStatus()

        // 更新有选择
        this.setData({
            selectAllStatus: !!this.data.selectIds.size
        })
    },
    // 选择所有员工
    selectWorker() {
        if (!this.data.selectAllStatus) {
            this.setData({
                showSelectTypeStatus: true,
            })
        } else {
            this.setData({
                selectAllStatus: false
            })
            this.unSelectAll()
        }
    },
    onCancelTypeSelect() {
        this.setData({
            showSelectTypeStatus: false
        })
    },
    // 选择已设置薪资
    selectSetAll() {
        const all = this.data.selectIds
        for (const i in this.data.workers) {
            console.log(this.data.workers)
            if (this.data.workers[i].price && this.data.workers[i].isLogout === 0) {
                this.data.workers[i].selected = true
                all.set(this.data.workers[i].userId, true)
            }
        }
        this.setData({
            selectIds: all,
            selectAllStatus: true,
            workers: this.data.workers
        })
        console.log(this.data.workers, 'workers')
        this.onCancelTypeSelect()
        this.upPayStatus()
    },
    // 选择长期工达成条件
    selectLongDayReachAll() {
        const all = this.data.selectIds
        for (const userId in this.data.workers) {
            if (this.data.workers[userId].satisfy === 1 && !this.data.workers[userId].isLogout) {
                all.set(userId, true)
                this.data.workers[userId].selected = true
            }
        }
        this.setData({
            selectIds: all,
            selectAllStatus: true,
            workers: this.data.workers
        })
        this.upPayStatus()
        this.onCancelTypeSelect()
    },
    // 全选
    selectAll(isPaySent) {
        const all = new Map()
        for (const i in this.data.showWorkers) {
            for (const userId in this.data.showWorkers[i]) {
                if (userId === 'length' || this.data.workers[userId].isLogout) {
                    continue
                }
                if(this.data.isRepeatTip && isPaySent !== 1) {
                    if(this.data.workers[userId].isPaySent) {
                        this.repeatPayTip(this.selectAll)
                        return
                    }
                }
                all.set(userId, true)
                this.data.workers[userId].selected = true
            }
        }
        this.setData({
            selectIds: all,
            selectAllStatus: true,
            workers: this.data.workers
        })
        this.onCancelTypeSelect()
        this.upPayStatus()
    },
    // 取消全选
    unSelectAll() {
        for (const i in this.data.workers) {
            this.data.workers[i].selected = false
        }
        this.data.selectIds.clear()
        this.setData({
            selectIds: this.data.selectIds,
            workers: this.data.workers
        })
        this.upPayStatus()
    },
    // 选择男
    selectMale(isPaySent) { // isPaySent  确认标识，标识用户已确认可以重复发薪
        const all = this.data.selectIds
        for (const userId in this.data.workers) {
            console.log(Boolean(), 'userId')
            if(this.data.isRepeatTip && isPaySent !== 1) {
                console.log('进入啦吗???')
                if(this.data.workers[userId].isPaySent) {
                    console.log('进入啦吗')
                    this.repeatPayTip(this.selectMale)
                    return
                }
            }
            if (this.data.workers[userId].sex === '0' && !this.data.workers[userId].isLogout) {
                all.set(userId, true)
                this.data.workers[userId].selected = true
            }
        }
        this.setData({
            selectIds: all,
            selectAllStatus: true,
            workers: this.data.workers
        })
        this.upPayStatus()
        this.onCancelTypeSelect()
    },
    // 选择女
    selectFemale(isPaySent) {
        const all = this.data.selectIds
        for (const userId in this.data.workers) {
            if(this.data.isRepeatTip && isPaySent !== 1) {
                if(this.data.workers[userId].isPaySent) {    
                    this.repeatPayTip(this.selectFemale)
                    return
                }
            }
            if (this.data.workers[userId].sex === '1' && !this.data.workers[userId].isLogout) {
                all.set(userId, true)
                this.data.workers[userId].selected = true
            }
        }
        this.setData({
            selectIds: all,
            selectAllStatus: true,
            workers: this.data.workers
        })
        this.upPayStatus()
        this.onCancelTypeSelect()
    },
    repeatPayTip(func) {
        wx.showModal({
            title: '确定重复发薪？',
            content: '已发过，确定重复发薪？',
            confirmText: '确认选中',
            success: (res) => {
                if (res.confirm) {
                    func(1)
                }
            }
        })
    },

    // 在员工选择变化时，对发薪按钮的可用性和转账金额等信息更新
    // 这里使用所有员工的信息而非使用显示的员工信息
    upPayStatus() {
        let payStatus = true
        let countPrice = 0
        const workers = this.data.workers
        for (const userId in workers) {
            if (this.data.selectIds.has(userId)) {
                if (!this.data.priceData.get(userId)) {
                    payStatus = false
                } else
                    countPrice += Number(this.data.priceData.get(userId)) * 1000
            }
        }
        countPrice = countPrice / 1000
        this.setData({
            countPayPrice: countPrice,
            countPayPeople: this.data.selectIds.size,
            payStatus: payStatus && this.data.selectIds.size
        })
        console.log(this.data.payStatus, '更改后的payStatus')
    },
    showPricePopup() {
        if(this.data.countPayPeople === 0) {
            app.toast('请至少选择一人')
            return
        }
        this.setData({
            setPriceStatus: true
        })
    },
    hidePricePopup() {
        this.setData({
            setPriceStatus: false,
            workerPrice: null
        })
    },
    // 为现在正在显示的并勾选的员工设置工资，有些虽然勾选了，但是不显示的不做更新
    setWorkerPrice() {
        if(/\.\./.test(this.data.workerPrice)) {
            app.toast('项目名称不规范，不可输入多个.')
            return
        }

        if (__wxConfig.envVersion !== 'develop' && Number(this.data.workerPrice) < 1 && Number(this.data.workerPrice) !== 0) {
            app.toast('员工薪资最小为1元')
            return
        }
        if (Number(this.data.workerPrice) === 0) {
            this.setData({
                workerPrice: null
            })
        }

        // 设置显示的价格和选择态
        for (const i in this.data.workers) {
            if (this.data.workers[i].selected) {
                this.data.workers[i].selected = false
                this.data.workers[i].price = this.data.workerPrice
                // 保存价格信息
                this.data.priceData.set(this.data.workers[i].userId, this.data.workerPrice)
            }
        }
        // 清空选择态
        this.data.selectIds.clear()
        this.setData({
            selected: this.data.selectIds,
            priceData: this.data.priceData,
            selectAllStatus: false,
            workers: this.data.workers
        })
        this.upPayStatus()
        this.hidePricePopup()
    },
    priceInputchange(event) {
        const val = event.detail.value.replace(/\s*/g, '')// 去除内容空格
        const dian = val.split('.')
        if (dian[1]) {
            dian[1] = dian[1].split('').slice(0, 2).join('')
            dian.splice(2)
            event.detail.value = dian.join('.')
        }
        let str = '0.'
        if(event.detail.value == '.' && event.detail.value.length <= 1) {
            event.detail.value = '0.'
            str = '0.'
        }
        if(str == '0.' && event.detail.value == '0..') {
            event.detail.value = str
        }
        console.log(val, 'valvalvalvalval')
        inputchange(event, this)
        if(val>Number(this.data.amountLimit)) {
            app.toast('个人发薪金额不可超过' + this.data.amountLimit + '元')
            this.setData({
                workerPrice: Number(this.data.amountLimit)
            })
            return
        }
        this.setData({
            workerPrice: val
        }) 
    },
    inputchange(event) {
        inputchange(event, this)
    },
    payWage(event) {
        if (!anit(event)) {
            return 0
        }
        if (!this.data.payStatus) {
            app.toast('不可发薪，请确保勾选员工均已设置金额')
            return 0
        }
        if (!this.data.remarks) {
            this.setData({
                setRemarkStatus: true
            })
            return
        }
        const emoji = /^[\w\u4e00-\u9fa5\-\+\=\.\/\*\!\！\,\，\s]+$/
        this.data.remarks = this.data.remarks.replace(/\s/g, '')
        if (!emoji.test(this.data.remarks)) {
            app.toast('申请理由不可使用特殊字符')
            return 0
        }


        const params = {}
        this.data.selectIds.forEach((value, key) => {
            params[key + ''] = this.data.priceData.get(key)
        })
        createPayFlow({
            projectId: this.data.projectId,
            peopleNum: this.data.countPayPeople,
            totalMoney: this.data.countPayPrice,
            remarks: this.data.remarks,
            createUserId: user.userId,
            companyId: user.companyId,
            flowCode: this.data.uuid,
            workDate: this.data.longDate ? this.data.longDate : this.data.date,
            params
        }).then(res => {
            console.log(res)
            wx.redirectTo({
                url: '/pages/success/success?title=申请成功&content=请等待上级审批后发薪&opinion=1&back=home&id=' + res 
            })
        })
    },
    // 搜索员工
    onSearch(event) {
        if (this.data.type)
            this.getLongProjectWorker(this.data.longSelectDate, event.detail.value)
        else
            this.getProjectWorker(event.detail.value)
    },
    onLongGoPay() {
        wx.navigateTo({
            url: '/packagePay/pages/pay-wage/pay-wage?id=' + this.data.projectId + '&type=' + this.data.type + '&longDate=' + this.data.longSelectDate+ '&processId=' + (this.data.processId||'')
        })
    },
    // 前往用户个人信息界面
    onGoWorker(event) {
        const workerId = event.currentTarget.dataset.id
        wx.navigateTo({
            url: '/pages/worker/index/index?id=' + workerId
        })
    },
    // 更新todo日期
    onLongMonthChange(event) {
        console.log(event, 'event更新todo日期')
        this.getLongProjectDate(event.detail.data)
    },
    // 查看未通过原因
    onSeeReason(event) {
        app.toast(event.currentTarget.dataset.msg)
    },
    // 跳转到字母位置
    onGoToLetter(event) {
        wx.vibrateShort({
            type: 'heavy'
        })
        const letter = event.currentTarget.dataset.letter
        const query = this.createSelectorQuery()
        query.selectViewport().scrollOffset()
        query.select('#letter-' + letter).boundingClientRect()
        query.exec(res => {
            const scrollTop = res[0].scrollTop
            const top = res[1]?.top ?? 0
            if (top)
                wx.pageScrollTo({
                    scrollTop: top + scrollTop
                })
            if (letter === '#') {
                wx.pageScrollTo({
                    scrollTop: 0
                })
            }
        })

        
    },
    // 拖动处理
    onDrag(event) {
        if (event.detail.source === 'touch') {
            shake(() => {
                const index = event.currentTarget.dataset.id
                if (event.detail.x > 5) {
                    this.setData({
                        ['workers.' + index + '.dragX']: 1000
                    })
                } else {
                    this.setData({
                        ['workers.' + index + '.dragX']: 0
                    })
                }
            }, 100)
        }

    },
    onGoTop(event) {
        const userId = event.currentTarget.dataset.id
        const top = this.data.showWorkers['置顶']
        const isTop = !this.data.workers[userId].isOnTheTop
        if (isTop) {
            top[userId] = this.data.workers[userId]
        } else {
            delete top[userId]
        }
        this.setData({
            ['showWorkers.置顶']: top,
            ['showWorkers.置顶.length']: isTop ? this.data.showWorkers['置顶'].length + 1 : this.data.showWorkers['置顶'].length - 1,
            ['workers.' + userId + '.dragX']: 1000,
            ['workers.' + userId + '.isOnTheTop']: isTop
        })
        setProjectWorkerTop({
            isOnTheTop: isTop + 0,
            id: this.data.workers[userId].id
        })
    }
})